<?php
namespace app\admin\controller;

use app\common\model\FreightTemplate;
use think\facade\Db;
use think\facade\View;

class Freight extends Base
{

    public function index()
    {
        if(IS_AJAX){
            $page = input('page');
            $limit = input('limit')?:15;
            $map = [];
            if($this->sid){
                $map['g.sid'] = $this->sid;
            }
            if(input('goods_id')){
                $map['g.goods_id'] = input('goods_id');
            }
            if(input('name')){
                $map['g.goods_name'] = ['like','%'.input('name').'%'];
            }
            if(input('sid')){
                $map['g.sid'] = input('sid');
            }

            $count = Db::name('freight_template')->where($map)->count();
            $field = '*';
            $list = Db::name('freight_template')
                ->field($field)
                ->where($map)
                ->order('template_id desc ')
                ->page($page,$limit)
                ->select();
            foreach($list as $k=>$v){

                $config_arr = json_decode($v['config'],true);
                $str = '';
                if($config_arr){
                    if($v['pstype']==1){
                        foreach($config_arr as $config){
                            $area_ids = $config['area_ids'];
                            if($area_ids){
                                $area_names =  Db::name('region')->where(['id'=>['in',$area_ids]])->column('name');
                                $area_names = implode(',',$area_names);
                            }else{
                                $area_names = '全国';
                            }
                            if($v['type']==0){
                                $prize_str = '首件'.$config['first_unit'].'件'.$config['first_money'].'元,每增加'.$config['continue_unit'].'件增加'.$config['continue_money'].'元';
                            }else{
                                $prize_str = '首重'.$config['first_unit'].'KG'.$config['first_money'].'元,每续重'.$config['continue_unit'].'KG'.'增加'.$config['continue_money'].'元';
                            }
                            $str .= '<b>'.$area_names.'</b><br/>'.$prize_str.'<br/>';
                        }
                    }

                }

                $v['area_str'] = $str;
                $v['w_time'] = date('Y-m-d H:i:s',$v['w_time']);
                $list[$k] = $v;
            }
            return json(['code'=>0,'msg'=>'查询成功','count'=>$count,'data'=>$list,'totalRow'=>[]]);
        }
        return View::fetch();
    }

    public function edit(){
        $id = input('id');
        $info = Db::name('freight_template')->where('template_id',$id)->find();
        View::assign('info',$info);
        $config_arr = [];
        if($info && $info['pstype']==0){
            if(!empty($info['config'])){
                $config_arr = json_decode($info['config'],true);
                foreach($config_arr as $k=>$config){
                    $area_ids = $config['area_ids']??'';
                    if($area_ids){
                        $area_names =  Db::name('region')->where(['id'=>['in',$area_ids]])->column('name');
                        $area_names = implode(',',$area_names);
                    }else{
                        $area_names = '全国';
                    }
                    $config['area_names'] = $area_names;
                    $config_arr[$k] = $config;
                }
            }else{
                $config_arr = [['area_ids'=>'','area_names'=>'全国','first_unit'=>0,'first_money'=>0,'continue_unit'=>0,'continue_money'=>0]];
            }
        }else{
            if($info){
                $config_arr = json_decode($info['config'],true);
            }else{
                $config_arr = [['area_ids'=>'','area_names'=>'全国','first_unit'=>0,'first_money'=>0,'continue_unit'=>0,'continue_money'=>0]];
            }
        }

        View::assign('config_arr',$config_arr);

        //$mendianArr = Db::name('mendian')->where('aid',aid)->order('id')->column('name','id');
        $mendianArr = [];
        View::assign('mendianArr',$mendianArr);

        $js_code_amap = tpCache('basic.js_code_amap');
        $map_key_amap = tpCache('basic.map_key_amap');
        View::assign('js_code_amap',$js_code_amap);
        View::assign('map_key_amap',$map_key_amap);
        return View::fetch();
    }
    /**
     *  保存运费模板
     * @throws \think\Exception
     */
    public function save()
    {
        $template_id = input('template_id/d');
        $template_name = input('template_name/s');
        $type = input('type/d');
        $pstype = input('pstype');
        $is_enable_default = input('is_enable_default/d');
        $config_list = input('config_list/a', []);
        $data = input();
//        $freightTemplateValidate = Loader::validate('FreightTemplate');
//        if (!$freightTemplateValidate->batch()->check($data)) {
//            $this->ajaxReturn(['status' => 0, 'msg' => '操作失败', 'result' => $freightTemplateValidate->getError()]);
//        }
        $freightTemplate = [];
        $freightTemplate['pstype'] = input('pstype');
        $freightTemplate['template_name'] = $template_name;
        $freightTemplate['type'] = $type;

//        $freightTemplate['is_enable_default'] = $is_enable_default;
        if($pstype==0){
            $area_ids_arr = $data['area_ids']??[];//配送区域
            $first_unit_arr = $data['first_unit']??[];//首重
            $first_money_arr = $data['first_money']??[];//首重费用
            $continue_unit_arr = $data['continue_unit']??[];//续重
            $continue_money_arr = $data['continue_money']??[];//续重费用
            $arr_recursive_length = count($area_ids_arr);
            $arr_unique = array_unique($area_ids_arr);
            $arr_unique_length = count($arr_unique);
            if($arr_recursive_length != $arr_unique_length){
                return json(['status' => 0, 'msg' => '配送区域存在重复区域']);
            }
            $config = [];
            foreach($area_ids_arr as $k=>$area_ids){
                if(empty($area_ids)){
                    //return json(['status' => 0, 'msg' => '请选择区域']);
                }
                $first_unit = $first_unit_arr[$k]??0;
                $first_money = $first_money_arr[$k]??0;
                $continue_unit = $continue_unit_arr[$k]??0;
                $continue_money = $continue_money_arr[$k]??0;
                $config[] = ['area_ids'=>$area_ids,'first_unit'=>$first_unit,'first_money'=>$first_money,'continue_unit'=>$continue_unit,'continue_money'=>$continue_money];
            }
        }else{
            $config = input('info/a');
        }

        $freightTemplate['config'] = json_encode($config);

        $freightTemplate['sort'] = input('sort');
        $freightTemplate['status'] = input('status');
        $freightTemplate['w_time'] = time();
        $freightTemplate['sid'] = SID?:1;
        if($template_id){
            Db::name('freight_template')->where('template_id',$template_id)->update($freightTemplate);
        }else{
            Db::name('freight_template')->insert($freightTemplate);
        }
       return json(['status' => 1, 'msg' => '保存成功', 'result' => '']);
    }

    /**
     * 删除运费模板
     * @throws \think\Exception
     */
    public function delete()
    {
        $ids = input('ids/a');
        $delete = Db::name('freight_template')->where(['template_id' =>['in', $ids]])->delete();
        if ($delete !== false) {
            return json(['status' => 1, 'msg' => '删除成功', 'result' => '']);
        } else {
            return json(['status' => 0, 'msg' => '删除失败', 'result' => '']);
        }
    }

    public function area(){
        $id = input('id');
        View::assign('id',$id);
        $area_ids = input('area_ids');
        View::assign('area_ids',$area_ids);
        return View::fetch();
    }
    public function getRegionNew(){
        $area_ids = input('area_ids');
        $area_ids = explode(',',$area_ids);
        $province_lists = Db::name('region')->where(['parent_id'=>0,'level'=>1])->field('id,name title')->select();
        foreach($province_lists as $k=>$province){
            $province['field'] = 'area_list[]';
            $province['checked'] = false;
            if(in_array($province['id'],$area_ids)){
                //$province['checked'] = true;
            }
            $province['spread'] = false;
            $city_lists =  Db::name('region')->where(['parent_id'=>$province['id'],'level'=>2])->field('id,name title')->select();
            foreach($city_lists as $ck=>$city){
                $city['field'] = 'area_list[]';
                $city['checked'] = false;
                if(in_array($city['id'],$area_ids)){
                    $city['checked'] = true;
                }
                $city['spread'] = true;
                $city_lists[$ck] = $city;
            }
//            foreach($city_lists as $ck=>$city){
//                $district_lists =  Db::name('region')->where(['parent_id'=>$city['id'],'level'=>3])->field('id,name title')->select();
//                $city_lists[$ck]['children'] = $district_lists;
//            }
            $province['children'] = $city_lists;
            $province_lists[$k] = $province;
        }
        return json(['status'=>1,'data'=>$province_lists]);
    }

}